package com.red.controller;

import com.alibaba.fastjson.JSON;
import com.red.result.ResponseTemplate;
import com.red.service.OrderService;
import com.red.vo.PayOrderRequestVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.*;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.*;

/**
 * @program: SpringBootDemos
 * @description:
 * @author: Kangsen
 * @create: 2021-08-27 15:42
 **/
@RestController
@Slf4j
public class indexController {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private OrderService orderService;

    @RequestMapping("/index")
    public String index(String key){
        List<String> keys = new ArrayList();
        if(StringUtils.isNoneBlank(key)){
            keys.add(key);
        }else{
            //redis模糊匹配KEY
            Cursor<String> cursor = scan(stringRedisTemplate, "*"+key+"*", 3000);
            while (cursor.hasNext()){
                //找到一次就添加一次
                keys.add(cursor.next());
            }
        }
        Map<String,Object> resultMap = new HashMap<>();
        for(String k:keys){
            Object value = stringRedisTemplate.opsForValue().get(k);
            if(Objects.isNull(value)){
                continue;
            }
            resultMap.put("key",k);
            resultMap.put("value",value);
            log.info(String.valueOf(resultMap));
        }
        return JSON.toJSONString(keys);
    }

    @PostMapping("/order/pay")
    public ResponseTemplate payOrder(@RequestBody PayOrderRequestVo requestVo){
        String tradeNo = orderService.payOrder(requestVo);
        return new ResponseTemplate(tradeNo);
    }

    private static Cursor<String> scan(StringRedisTemplate stringRedisTemplate, String match, int count){
        ScanOptions scanOptions = ScanOptions.scanOptions().match(match).count(count).build();
        RedisSerializer<String> redisSerializer = (RedisSerializer<String>) stringRedisTemplate.getKeySerializer();
        return (Cursor) stringRedisTemplate.executeWithStickyConnection((RedisCallback) redisConnection ->
                new ConvertingCursor<>(redisConnection.scan(scanOptions), redisSerializer::deserialize));
    }
}
